import {Injectable} from "@angular/core";
import {SqliteService} from "./sqlite.service";
import {AppService} from "./app.service";
import {AppConfig} from "../../app/app.config";
import {ResDataModel} from "../models/res-data-model";

@Injectable()
export class SysDictService {
  constructor(private sqliteService: SqliteService,
              private appService: AppService) {
  }

  /**
   * 在SQLite中创建字典表
   */
  createSysDictTable(){
    var sql =`
      CREATE TABLE
      IF
        NOT EXISTS app_sys_dict (
        cId VARCHAR2 ( 32 ) PRIMARY KEY,
        pId VARCHAR2 ( 32 ),
        dictTypeCode VARCHAR2 ( 32 ) NOT NULL,
        dictCode VARCHAR2 ( 32 ) ,
        dictValue VARCHAR2 ( 200 )
        );`
    this.sqliteService.execSql(sql,[]).then(data=>{
      console.log(data)
    }).catch(err =>{
      console.error(err);
    })
  }

  /**
   * 从服务端同步字典信息（全量）
   */
  sysnDicts(){
    let postParam = {
      dictTypeCodes:AppConfig.DictTypeCodes.join(',')
    }
    //先删除原来的数据
    this.sqliteService.execSql('delete from app_sys_dict',[]);
    //从服务器获取数据
    this.appService.httpPost('AppDictCtrl_loadDict',postParam,null,(res:ResDataModel)=>{
      let datas = res.datas;
      var cId = 1;
      datas.forEach(data=>{
        var dictTypeCode = data.dataName;
        let values:any[] = data.data;
        values.forEach(value => {
          var code = value.code;
          var caption = value.caption;
          var sql = "Insert into app_sys_dict values (?,'',?,?,?)";
          var param:Array<string> = [cId+"",dictTypeCode,code,caption];
          //插入SQLite
          this.sqliteService.execSql(sql,param);
          //主键自增
          cId++;
        })
      })
    },false)
  }

  /**
   * 根据字典类型获取字典项数组
   * @param {string} dictTypeCode
   * @returns {any[]}
   */
  getDictsByDictTypeCode(dictTypeCode:string):Promise<any[]>{
    var sql = "select dictCode as code,dictValue as caption from app_sys_dict where dictTypeCode = ?";
    var params:Array<any> = [];
    params.push(dictTypeCode);
    //var param = [dictTypeCode];
    return new Promise((resolve, reject) => {
      this.sqliteService.execSql(sql,params).then((res)=>{
        let resultSet = [];
        for(var i=0;i<res.res.rows.length;i++){
          console.log(res.res.rows.item(i));
          resultSet.push(res.res.rows.item(i));
        }
        resolve(resultSet);
      },(res)=>{
        console.error(res);
        reject(res.err);
      }).catch(err=>{
        reject(err.err);
      })
    })
  }

  /**
   * 获取字典项的值
   * @param {string} dictTypeCode
   * @param {string} code
   */
  getValue(dictTypeCode:string,code:string):Promise<any>{
    var sql = "select dictValue as caption from app_sys_dict t where t.dictTypeCode = ? and dictCode = ?";
    var param = [dictTypeCode,code];
    return new Promise((resolve, reject) => {
      this.sqliteService.execSql(sql,param).then((res)=>{
        resolve(res.res);
      },(res)=>{
        console.error(res);
        reject(res.err);
      }).catch(err=>{
        reject(err.err);
      })
    })
  }
}
